# -*- encoding: utf-8 -*-
from Common.mysql import db
from src.Bugs.Database.bugs_database import BugData, BugDataSchema
from src.Bugs.Database.bug_comment_database import BugCommentData
from src.Bugs.Database.bug_history_database import BugDataHistory
from src.User.Database.user_database import User, UserSchema
from src.Bugs.Function.send_lark_massege import SendLarkMessage
from sqlalchemy.exc import SQLAlchemyError
from Common.yaml_method import YamlMethod
from Common.public_method import utc_8


class UpdateBug:
    """
    更新缺陷相关接口
    """

    def get_open_id(self, name):
        """
        给用户发送飞书消息
        :param name:
        :return:
        """
        # 查询用户飞书登录的open_id
        user = User.query.filter_by(realName=name).first()
        user_schema = UserSchema()
        user_data = user_schema.dump(user)
        open_id = user_data['openId']
        if open_id:
            return open_id
        else:
            return None

    def update_bug(self, bug_id, title, describe, sprint, severity, level, handler, responsible, bug_type, platform, status):
        """
        更新缺陷数据
        :param bug_id: 缺陷ID
        :param title: 缺陷标题
        :param describe: 缺陷描述
        :param sprint: 迭代
        :param severity: 严重程度
        :param level: 缺陷等级
        :param handler: 处理人
        :param responsible: 责任人
        :param bug_type: 缺陷类型
        :param platform: 软件平台
        :param status: 缺陷状态
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        # 判断缺陷是否存在
        bug = BugData.query.filter_by(id=bug_id).first()
        if bug:
            # 取出缺陷信息
            bug_schema = BugDataSchema()
            bug_data = bug_schema.dump(bug)

            if responsible:
                # 如果改了责任人，处理人改成新责任人，缺陷状态更新为新，飞书通知新责任人，飞书通知创建人
                handler = responsible
                status = '新'
                # 飞书通知新责任人
                responsible_open_id = self.get_open_id(responsible)
                if responsible_open_id:
                    msg_title = '新增bug通知'
                    SendLarkMessage().send_lark_message(responsible_open_id, msg_title, bug_data['title'], bug_data['level'], bug_data['severity'], bug_data['create_user'])
                # 飞书通知创建人
                creator_open_id = self.get_open_id(bug_data['create_user'])
                if creator_open_id:
                    msg_title = '重新指派责任人：%s -> %s' % (bug_data['responsible'], responsible)
                    SendLarkMessage().send_lark_message(creator_open_id, msg_title, bug_data['title'],
                                                        bug_data['level'], bug_data['severity'], bug_data['create_user'])
            if handler:
                # 如果更改了处理人，飞书通知处理人
                open_id = self.get_open_id(handler)
                msg_title = 'bug处理人由 %s 转为了你' % (bug_data['handler'])
                SendLarkMessage().send_lark_message(open_id, msg_title, bug_data['title'], bug_data['level'], bug_data['severity'], bug_data['create_user'])
            else:
                if status:
                # 如果没改处理人，则自动更新处理人
                    # 当状态为"新"、"接受处理"时，不变更下一阶段处理人，否则自动更新处理人
                    if status == '新':
                        # 不变更处理人
                        handler = bug_data['handler']
                    if status == '接受处理':
                        # 不变更处理人
                        handler = bug_data['handler']
                    if status == '已解决':
                        # 处理人变更为创建人
                        handler = bug_data['create_user']
                    if status == '已关闭':
                        # 清空处理人
                        handler = ' '
                    if status == '重新打开':
                         # 处理人变更为责任人
                        handler = bug_data['responsible']
                    if status == '已拒绝':
                        # 处理人变更为创建人
                        handler = bug_data['create_user']

            # 发送飞书通知（状态变化：已解决、重新打开、已拒绝）
            if status != bug_data['status'] and status in ("已解决", "重新打开", "已拒绝"):
                open_id = self.get_open_id(handler)
                msg_title = 'bug状态变更：%s -> %s' % (bug_data['status'], status)
                SendLarkMessage().send_lark_message(open_id, msg_title, bug_data['title'], bug_data['level'], bug_data['severity'], bug_data['create_user'])

            old_is_reopen = bug_data['is_reopen']
            # 然后更新bug_data数据库
            if title:
                bug.title = title
            if describe:
                bug.describe = describe
            if sprint:
                bug.sprint = sprint
            if severity:
                bug.severity = severity
            if level:
                bug.level = level
            if handler:
                bug.handler = handler
            if bug_type:
                bug.bugType = bug_type
            if platform:
                bug.platform = platform
            if status:
                bug.status = status
                if status == '重新打开':
                    # 如果是重新打开，则 is_reopen 字段值更新为 1
                    if old_is_reopen:
                        bug.is_reopen = old_is_reopen + 1
                    else:
                        bug.is_reopen = 1
            if responsible:
                bug.responsible = responsible
            try:
                db.session.commit()
            except SQLAlchemyError:
                db.session.rollback()
                res = {
                    'code': code[6],
                    'data': [],
                    'message': '更新缺陷信息失败'
                }
                return res
            res = {
                'code': code[0],
                'data': [],
                'message': '更新缺陷信息成功'
            }
            return res
        else:
            res = {
                'code': code[3],
                'data': [],
                'message': '缺陷不存在'
            }
            return res

    def insert_comment(self, bug_id, comment, create_user):
        """
        更新comment数据库
        :param bug_id: 缺陷ID
        :param comment: 缺陷评论
        :param create_user: 创建人
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        # 判断缺陷是否存在
        bug = BugData.query.filter_by(id=bug_id).first()
        if bug:
            create_time = utc_8()
            # 数据插入数据库
            bug_comment = BugCommentData(bug_id=bug_id, comment=comment, create_time=create_time,
                                         create_user=create_user)
            db.session.add(bug_comment)
            db.session.commit()
            bug = BugData.query.filter_by(id=bug_id).first()
            bug_schema = BugDataSchema()
            bug_data = bug_schema.dump(bug)
            open_id = ''
            # 飞书通知创建人和当前处理人
            if create_user == bug_data['create_user']:
                open_id = self.get_open_id(bug_data['responsible'])
            if create_user == bug_data['responsible']:
                open_id = self.get_open_id(bug_data['create_user'])
            if open_id:
                msg_title = '新增bug评论'
                contents = '·bug标题：%s \n·bug评论：%s' % (bug_data['title'], comment)
                SendLarkMessage().send_lark_message(open_id, msg_title, contents, bug_data['level'],
                                                    bug_data['severity'], bug_data['create_user'])
            res = {
                'code': code[0],
                'message': 'success',
                'data': {}
            }
            return res
        else:
            res = {
                'code': code[3],
                'data': [],
                'message': '缺陷不存在'
            }
            return res

    @staticmethod
    def insert_history(bug_id, title, describe, sprint, severity, level, handler, responsible, bug_type, platform,
                       status, comment, create_user):
        """
        将修改记录插入到history表中
        :param bug_id: 缺陷ID
        :param title: 缺陷标题
        :param describe: 缺陷描述
        :param sprint: 迭代
        :param severity: 严重程度
        :param level: 缺陷等级
        :param handler: 处理人
        :param responsible: 责任人
        :param bug_type: 缺陷类型
        :param platform: 软件平台
        :param status: 缺陷状态
        :param comment: 缺陷ID
        :param create_user: 创建人
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        update_time = utc_8()
        update_key = []
        if title:
            update_key.append('缺陷标题')
        if describe:
            update_key.append('缺陷内容')
        if sprint:
            update_key.append('迭代')
        if severity:
            update_key.append('严重程度')
        if level:
            update_key.append('缺陷等级')
        if bug_type:
            update_key.append('缺陷类型')
        if platform:
            update_key.append('软件平台')
        if status:
            update_key.append('缺陷状态')
        if comment:
            update_key.append('缺陷评论')
        if handler:
            update_key.append('处理人')
        if responsible:
            update_key.append('责任人')

        # 数据插入数据库
        bug_history = BugDataHistory(bug_id=bug_id, update_key=str(update_key), update_time=update_time,
                                     update_user=create_user)
        db.session.add(bug_history)
        db.session.commit()

        res = {
            'code': code[0],
            'message': 'success',
            'data': {}
        }

        return res
